import { DirectiveBinding } from 'vue';

async function lazyFun(el:HTMLImageElement, binding:DirectiveBinding) {
    // el.src 去设置默认图片
    const defimg = await import('@/assets/vue.svg')
                        
    el.src = defimg.default

    // 监听new IntersectionObserver(enr) 
    const obser = new IntersectionObserver((enr) => {
        const curEnr = enr[0]
        // 去监听img是否在视口内，在enr.radtio > 0 此时替换图片 同时关闭监听
        if(curEnr.intersectionRatio > 0) {
            setTimeout(() => {
                el.src = binding.value
            },2000)
            obser.unobserve(el)
        }
    })
    obser.observe(el)
}
export function vLazy(app: any) {
    app.directive('lazy', {
        mounted(el:HTMLImageElement, binding:DirectiveBinding) {
            lazyFun(el, binding)
        }
    })
}